##################################################################
# File : /lua/user/userscriptcommand.lua
# Description : User layer ability handling
# Author : GPG
##################################################################

local CM = import('/lua/ui/game/commandmode.lua')

--[[
The user wants to issue an script order in the current command mode. This
function validates the request. If the request is valid we set 
UserValidated to allow the order to be issued. If it's not valid we end the 
commandmode or do nothing depending on the context.

VerifyScriptCommand should return a result table of the following format:
result = {
   string AbilityName - What ability to execute
   string TaskName - Which task class to execute (e.g. AbilityTask, SkillTask)
   bool UserValidated - Whether or not this request has been validated
   table AuthorizedUnits - List of units to issue the command to
}
--]]

local function VerifyCommand(data)
    local result = {
        UserValidated = false,
        Location = data.Target.Position
    }

    if not data.Target.BlueprintId then
        WARN('VerifyCommand: No target blueprint specified.')
        return result
    end
    
    local bp = __blueprints[data.Target.BlueprintId]
    
    if not bp or not bp.ScriptedAction then
        WARN('VerifyCommand: Target does not have scripted action specified.')
        return result
    end
    
    result = import(bp.ScriptedAction).VerifyCommand(data,result)
    return result
end

local function VerifyOrder(mode,data)
    local result = {
        TaskName = mode[2].TaskName,
        UserValidated = false,
        Location = data.Target.Position
    }
    
    if mode[1] != "order" then
        WARN('VerifyScriptCommand() called when command mode is not "order"')
        return result
    end
    
    if mode[2].name != "RULEUCC_Script" then
        WARN('VerifyScriptCommand() called when command name is not "Script"')
        return result
    end
    
    #LOG('verify script: ',mode[2].UserVerifyScript)
    if mode[2].UserVerifyScript then
        import(mode[2].UserVerifyScript).VerifyScriptCommand(data,result)
    else
        result.AuthorizedUnits = data.Units
        result.UserValidated = true
    end
    
    return result
end

function VerifyScriptCommand(data)
    local mode = CM.GetCommandMode()
   
    if mode[1] and mode[2] then
        # We have a commandmode set (started from script)
        return VerifyOrder(mode,data)
    else
        # We clicked on something that resulted in a ScriptAction
        return VerifyCommand(data)
    end
end